package com.his.exception;

import com.his.common.Rsp;
import io.jsonwebtoken.ClaimJwtException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

/**全局异常处理类
 * @author dawn
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 处理前端传过来的参数校验异常
     *
     * @param e 异常
     * @return 返回给前端的数据
     */
    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class, ConstraintViolationException.class})
    public Rsp paramCheck(Exception e) {
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException m = (MethodArgumentNotValidException) e;
            BindingResult result = m.getBindingResult();
            for (FieldError fieldError : result.getFieldErrors()) {
                return Rsp.fail().msg(fieldError.getDefaultMessage());
            }
        } else if (e instanceof BindException) {
            BindException b = (BindException) e;
            for (FieldError fieldError : b.getFieldErrors()) {
                return Rsp.fail().msg(fieldError.getDefaultMessage());
            }
        } else {
            ConstraintViolationException c = (ConstraintViolationException) e;
            Set<ConstraintViolation<?>> set = c.getConstraintViolations();
            for (ConstraintViolation<?> violation : set) {
                return Rsp.fail().msg(violation.getMessage());
            }
        }
        return null;
    }

    /**
     * token解析异常
     * @param e 异常信息
     * @return 异常返回值
     */
    @ExceptionHandler(ClaimJwtException.class)
    public Rsp JWTCheck(ClaimJwtException e){
        return Rsp.fail().code(50008).msg("token已过期请重新登录");
    }


    /**
     * 非法参数异常
     * @param e 异常信息
     * @return 异常返回值
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public Rsp testException(IllegalArgumentException e){
        e.printStackTrace();
        return Rsp.fail().msg("非法参数异常");
    }

    @ExceptionHandler(Exception.class)
    public Rsp otherException(Exception e) {
        e.printStackTrace();
        return Rsp.fail().msg("这是个未知异常");
    }
}
